package com.pay.sdk.zftzl.usage;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;


import java.util.ArrayList;
import java.util.List;

import com.pay.sdk.zftzl.R;

import sdk.pay.PayUtil;
import sdk.pay.listener.PayGetPayTypeListener;
import sdk.pay.listener.PayUtilCallBack;
import sdk.pay.model.PayTypeModel;
import sdk.pay.model.TokenParam;


public class PayActivity extends Activity implements PayUtilCallBack {
    protected Dialog mProgressDialog;
    private GridView mGridView;
    private TextView mPayName;
    private TextView mPayPrice;
    private PayTypeGridviewAdapter mAdapter;
    private int mCheckedId = -1;
    private static TokenParam mTokenParam;
    private static Activity mActivity;
    private PayParameter mPayParameter;
    private PayUtil mPayUtil;
    private boolean mPaySucceed;
    private Toast mToast;
    /**
     * 建议商户信息由服务器获取,
     * 不推荐商户支付信息存放在客户端
     * 非常不推荐商户支付密钥存放在客户端
     * demo由于展示原因,在手机端进行
     * It is recommended that the business information be obtained by the server,
     * not recommended for merchant payment message stored on the client
     * very not recommended for merchant payment keys stored on the client
     * demo as a result of the show, in the mobile terminal
     **/
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            List<PayTypeModel> payTypeModelList = mPayUtil.getPayTypeModels();
            if (payTypeModelList == null || payTypeModelList.size() == 0) {
                return;
            }
            dismiss();
            if (payTypeModelList.size() > 0) {
                mAdapter.setList(payTypeModelList);
                mAdapter.Portrait(isPortrait());
                if (mCheckedId == -1) {
                    for (PayTypeModel typeModel : payTypeModelList) {
                        if ("ZFBSDK".equals(typeModel.getTypeid())) {
                            mCheckedId = payTypeModelList.indexOf(typeModel);
                            break;
                        } else {
                            mCheckedId = 0;
                        }
                    }
                }
                mAdapter.selectItem(mCheckedId);
                mGridView.setAdapter(mAdapter);
            } else {
                Toast.makeText(PayActivity.this, "Did not get the payment!", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_layout);
        mPayParameter = new PayParameter();
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        mAdapter = new PayTypeGridviewAdapter(this, new ArrayList<PayTypeModel>());
        mPayUtil = new PayUtil(mActivity, mTokenParam.getP1_appid(), mTokenParam.getKey(),
                mTokenParam.getVector(), this, true);
        mProgressDialog = ProgressDialog.show(PayActivity.this, "", getString(R.string.init_tips), false, true, null);
        // getPayTypes为获取支付列表接口如果有自己的界面，可删掉相关代码
        // getPayTypes can delete the phase code if it has its own interface to get the payment list interface
        mPayUtil.getPayType(getTokenParam(), new PayGetPayTypeListener() {
            @Override
            public void onPayDataResult() {
                runOnUiThread(mRunnable);
            }
        });
        initView();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.pay_layout);
        initView();
        mAdapter.Portrait(isPortrait());
        mGridView.setAdapter(mAdapter);
    }

    private boolean isPortrait() {
        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    private void initView() {
        initWidgets();
        mPayName.setText(mTokenParam.getP17_product());
        mPayPrice.setText(String.format("%s元", mTokenParam.getP3_money()));
    }

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.pay.close");
        localBroadcastManager.registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismiss();
        if (mPaySucceed)
            finish();
    }

    public static void startActivity(Activity activity, TokenParam tokenParam) {
        Intent intent = new Intent(activity, PayActivity.class);
        mActivity = activity;
        mTokenParam = tokenParam;
        activity.startActivity(intent);
    }

    private TokenParam getTokenParam() {
        return mTokenParam;
    }

    private void initWidgets() {
        mPayName = (TextView) findViewById(R.id.junpay_TextView_name);
        mPayPrice = (TextView) findViewById(R.id.junpay_TextView_price);
        mGridView = (GridView) findViewById(R.id.junpay_listview);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCheckedId = position;
                mAdapter.selectItem(mCheckedId);
            }
        });
        findViewById(R.id.junpay_button_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProgressDialog = ProgressDialog.show(PayActivity.this, "", getString(R.string.pay_info), false, true, null);
                if (mCheckedId >= 0) {
                    final String typeId = getTypeId(mCheckedId);
                    mPayParameter.setPaySignListener(new PayParameter.PaySignCallback() {
                        @Override
                        public void paySign(TokenParam payParasmeterModel) {
                            mTokenParam = payParasmeterModel;
                            mPaySucceed = true;
                            mPayUtil.pay(typeId, getTokenParam());
                        }

                        @Override
                        public void failureSign(String str) {
                            dismiss();
                            showToast(str);
                        }
                    });
                    mPayParameter.getPaySign(PayActivity.this, mTokenParam.getP3_money(), typeId, mTokenParam.getP2_orderNumber(), mTokenParam.getP6_orderTime());
                } else {
                    Toast.makeText(PayActivity.this, "Payment has not yet chosen", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private String getTypeId(int index) {
        List<PayTypeModel> list = mPayUtil.getPayTypeModels();
        PayTypeModel model = list.get(index);
        return model.getTypeid();
    }

    @Override
    public void onPayException(String exceptionmessage) {
        dismiss();
        if (mPaySucceed) {
            mPaySucceed = false;
            mActivity = null;
            finish();
        }
    }

    private void showToast(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mToast.setText(str);
                mToast.show();
            }
        });
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
}